package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import com.example.myapplication.bean.Food;
import android.database.sqlite.SQLiteDatabase;
import android.database.Cursor;
import android.widget.TableRow;
import android.view.Gravity;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import androidx.appcompat.app.AlertDialog;
import android.text.InputType;

// 定义一个功能类
public class FunctionActivity extends AppCompatActivity {
    // 定义私有成员变量
    private static final String TAG = "FunctionActivity";
    private String host = "tcp://8.138.215.14:1883"; // MQTT 服务器地址
    private String userName = "MyAPP"; // 用户名
    private String passWord = "12345678"; // 密码
    private Button btn_add,bnt_add_fans,bnt_close_fans,bnt_open_light,bnt_close_light; // 添加按钮
    private TextView text_temp, text_humi; // 温度和湿度显示控件
    private MqttClient client; // MQTT 客户端
    private MqttConnectOptions options; // MQTT 连接选项
    private Handler handler; // 用于处理接收到的消息
    private ScheduledExecutorService scheduler; // 定时任务执行器
    private String mqtt_id = "bingxiang"; // MQTT 客户端 ID
    private String mqtt_sub_topic = "test"; // 订阅的主题
    private String mqtt_pub_topic = "led"; // 发布的主题

    private MySQLiteOpenHelper dbHelper; // 数据库帮助类
    private TableLayout tableLayout; // 显示食物信息的 TableLayout

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_function_main);

        // 初始化 TableLayout
        tableLayout = findViewById(R.id.tableLayout);

        Mqtt_init(); // 初始化 MQTT 客户端

        startReconnect(); // 启动重连机制

        dbHelper = new MySQLiteOpenHelper(this); // 初始化数据库帮助类

        // 获取layout的布局界面的元素对象
        btn_add = findViewById(R.id.btn_add); // 获取添加按钮
        text_temp = findViewById(R.id.text_temp); // 获取温度 TextView
        text_humi = findViewById(R.id.text_humi); // 获取湿度 TextView
        bnt_add_fans = findViewById(R.id.bnt_add_fans); // 获取打开风扇 ButtonView
        bnt_close_fans = findViewById(R.id.bnt_close_fans); // 获取关闭风扇 ButtonView

        bnt_add_fans.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String message = String.format("1");
                // 发布消息到指定主题
                publishmessageplus(mqtt_pub_topic, message);
                // 弹出Toast提示用户打开成功
                Toast.makeText(FunctionActivity.this, "开风扇", Toast.LENGTH_SHORT).show();
            }
        });
        bnt_close_fans.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String message = String.format("0");
                // 发布消息到指定主题
                publishmessageplus(mqtt_pub_topic, message);
                // 弹出Toast提示用户关闭成功
                Toast.makeText(FunctionActivity.this, "关风扇", Toast.LENGTH_SHORT).show();
            }
        });
        // 设置按钮点击事件，添加食物信息
        btn_add.setOnClickListener(v -> {
            // 创建意图对象，执行界面跳转
            Intent intent = new Intent(FunctionActivity.this, InputFoodActivity.class);
            startActivity(intent); // 跳转到新页面
        });
        displayFoodData(); // 刷新食物数据展示

        handler = new Handler(Looper.myLooper()) {
            @SuppressLint("SetTextI18n")
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what){
                    case 1: //开机校验更新回传
                        break;
                    case 2:  // 反馈回传

                        break;
                    case 3:  //MQTT 收到消息回传   UTF8Buffer msg=new UTF8Buffer(object.toString());

                        System.out.println(msg.obj.toString());   // 显示MQTT数据
                        break;
                    case 30:  //连接失败
                        Toast.makeText(FunctionActivity.this,"连接失败" , Toast.LENGTH_SHORT).show();
                        break;
                    case 31:   //连接成功
                        Toast.makeText(FunctionActivity.this,"连接成功" ,Toast.LENGTH_SHORT).show();
                        try {
                            client.subscribe(mqtt_sub_topic,1);
                        } catch (MqttException e) {
                            e.printStackTrace();
                        }
                        break;
                    default:
                        break;
                }
            }
        };
        /* -------------------------------------------------------------------------------------- */
        // 启动定时器定期刷新表格
        startTableRefresh();
    }

    private void startTableRefresh() {
        // 启动定时器 + 线程池定期刷新table食物信息表
        scheduler = Executors.newScheduledThreadPool(1);
        scheduler.scheduleAtFixedRate(() -> {
            runOnUiThread(this::displayFoodData);
        }, 0, 2, TimeUnit.SECONDS); // 每2秒刷新一次表格
    }

    // 刷新表格，显示食物数据
    private void displayFoodData() {
        // 清空除表头之外的所有行
        tableLayout.removeViewsInLayout(1, tableLayout.getChildCount() - 1);

        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT * FROM food", null);

        while (cursor.moveToNext()) {
            // 获取数据
            @SuppressLint("Range") int id = cursor.getInt(cursor.getColumnIndex("id"));
            @SuppressLint("Range") String name = cursor.getString(cursor.getColumnIndex("name"));
            @SuppressLint("Range") String storeDate = cursor.getString(cursor.getColumnIndex("store_date"));
            @SuppressLint("Range") String expiryDate = cursor.getString(cursor.getColumnIndex("expiry_date"));
            @SuppressLint("Range") int count = cursor.getInt(cursor.getColumnIndex("count"));

            int remainingDays = calculateRemainingDays(expiryDate);

            // 创建新行
            TableRow row = new TableRow(this);
            // 这里可以设置行的属性，例如边距、背景等

            // 创建各列的 TextView
            TextView nameTextView = new TextView(this);
            nameTextView.setText(name);
            nameTextView.setGravity(Gravity.CENTER);

            TextView storeDateTextView = new TextView(this);
            storeDateTextView.setText(storeDate);
            storeDateTextView.setGravity(Gravity.CENTER);

            TextView countTextView = new TextView(this);
            countTextView.setText(String.valueOf(count));
            countTextView.setGravity(Gravity.CENTER);

            TextView remainingDaysTextView = new TextView(this);
            remainingDaysTextView.setText(String.valueOf(remainingDays));
            remainingDaysTextView.setGravity(Gravity.CENTER);

            // 创建“取出”操作按钮
            Button takeOutButton = new Button(this);
            takeOutButton.setText("取出");
            takeOutButton.setOnClickListener(v -> {
                // 当点击“取出”按钮时，弹出对话框输入取出数量
                Food food = new Food(id, name, storeDate, expiryDate, count);
                showTakeOutDialog(food);
            });

            // 将各个组件添加到行中
            row.addView(nameTextView);
            row.addView(storeDateTextView);
            row.addView(countTextView);
            row.addView(remainingDaysTextView);
            row.addView(takeOutButton);

            // 将行添加到 TableLayout
            tableLayout.addView(row);
        }

        cursor.close();
        db.close();
    }
    private void showTakeOutDialog(final Food food) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("请输入取出数量");

        // 创建输入框
        final EditText input = new EditText(this);
        input.setInputType(InputType.TYPE_CLASS_NUMBER);
        input.setHint("取出数量");
        builder.setView(input);

        builder.setPositiveButton("确定", (dialog, which) -> {
            String inputStr = input.getText().toString();
            if (inputStr.isEmpty()) {
                Toast.makeText(FunctionActivity.this, "请输入数量", Toast.LENGTH_SHORT).show();
                return;
            }

            int takeOutQty;
            try {
                takeOutQty = Integer.parseInt(inputStr);
            } catch (NumberFormatException e) {
                Toast.makeText(FunctionActivity.this, "请输入有效的数字", Toast.LENGTH_SHORT).show();
                return;
            }

            int currentCount = food.getCount();
            if (takeOutQty > currentCount) {
                Toast.makeText(FunctionActivity.this, "库存不足", Toast.LENGTH_SHORT).show();
            } else if (takeOutQty == currentCount) {
                // 数量相等，删除记录
                deleteFoodFromDatabase(food.getId());
                Toast.makeText(FunctionActivity.this, "库存清空，记录已删除", Toast.LENGTH_SHORT).show();
            } else {
                // 数量减少，更新记录
                updateFoodCount(food.getId(), currentCount - takeOutQty);
                Toast.makeText(FunctionActivity.this, "成功取出 " + takeOutQty + " 个", Toast.LENGTH_SHORT).show();
            }
            displayFoodData(); // 刷新表格
        });

        builder.setNegativeButton("取消", (dialog, which) -> dialog.cancel());
        builder.show();
    }


    // 计算剩余天数
    private int calculateRemainingDays(String expiryDate) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        try {
            Date expiry = dateFormat.parse(expiryDate);
            Date today = new Date(); // 当前日期

            long diffInMillis = expiry.getTime() - today.getTime();
            long diffInDays = TimeUnit.DAYS.convert(diffInMillis, TimeUnit.MILLISECONDS);

            return (int) diffInDays; // 返回剩余天数
        } catch (ParseException e) {
            e.printStackTrace();
            return -1; // 解析失败时返回 -1
        }
    }

    // 删除食物数据
    private void deleteFoodFromDatabase(String name) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        db.delete("food", "name = ?", new String[]{name});
        db.close();
    }
    private void deleteFoodFromDatabase(int id) {
        dbHelper.deleteFoodById(id);
    }
    private void updateFoodCount(int id, int newCount) {
        dbHelper.updateFoodCount(id, newCount);
    }

    // 提取 JSON 字符串中的某个值
    private String extractValue(String jsonString, String key) {
        String value = "0";
        int keyIndex = jsonString.indexOf(key);
        if (keyIndex != -1) {
            String tempString = jsonString.substring(keyIndex + key.length());
            int commaIndex = tempString.indexOf(",");
            if (commaIndex != -1) {
                value = tempString.substring(0, commaIndex);
            } else {
                int endIndex = tempString.indexOf("}");
                if (endIndex != -1) {
                    value = tempString.substring(0, endIndex);
                }
            }
        }
        return value;
    }

    // 将字符串转换为浮点数
    private float parseToFloat(String value) {
        try {
            return Float.parseFloat(value);
        } catch (NumberFormatException e) {
            Log.e(TAG, "无效的浮动格式: " + value, e);
            return 0;
        }
    }

    // MQTT初始化
    private void Mqtt_init()
    {
        try {
            //host为主机名，test为clientid即连接MQTT的客户端ID，一般以客户端唯一标识符表示，MemoryPersistence设置clientid的保存形式，默认为以内存保存
            client = new MqttClient(host, mqtt_id,
                    new MemoryPersistence());
            //MQTT的连接设置
            MqttConnectOptions options = new MqttConnectOptions();
            //设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录，这里设置为true表示每次连接到服务器都以新的身份连接
            options.setCleanSession(false);
            //设置连接的用户名
            options.setUserName(userName);
            //设置连接的密码
            options.setPassword(passWord.toCharArray());
            // 设置超时时间 单位为秒
            options.setConnectionTimeout(10);
            // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线，但这个方法并没有重连的机制
            options.setKeepAliveInterval(20);
            //设置回调
            client.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable cause) {
                    //连接丢失后，一般在这里面进行重连
                    System.out.println("connectionLost----------");
                    //startReconnect();
                }
                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                    //publish后会执行到这里
                    System.out.println("deliveryComplete---------"
                            + token.isComplete());
                }
                @Override
                public void messageArrived(String topicName, MqttMessage message) throws Exception {
                    String rawData = new String(message.getPayload(), "UTF-8");

                    // 使用正则表达式匹配温度值（支持整数/小数）
                    Pattern tempPattern = Pattern.compile("\"temp\"\\s*:\\s*(\\d+\\.?\\d*)");
                    Matcher tempMatcher = tempPattern.matcher(rawData);
                    String temp = tempMatcher.find() ? tempMatcher.group(1) : "0";

                    // 使用正则表达式匹配湿度值
                    Pattern humiPattern = Pattern.compile("\"humi\"\\s*:\\s*(\\d+\\.?\\d*)");
                    Matcher humiMatcher = humiPattern.matcher(rawData);
                    String humi = humiMatcher.find() ? humiMatcher.group(1) : "0";

                    if (temp != null && !temp.isEmpty() && humi != null && !humi.isEmpty()) {
                        text_temp.setText("温度：" + temp);
                        text_humi.setText("湿度：" + humi);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 连接MQTT服务器，在新线程中执行连接操作，避免阻塞UI线程
     */
    private void Mqtt_connect() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if(!(client.isConnected()) )  //如果还未连接
                    {
                        MqttConnectOptions options = null;
                        client.connect(options);
                        Message msg = new Message();
                        msg.what = 31;
                        handler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Message msg = new Message();
                    msg.what = 30;
                    handler.sendMessage(msg);
                }
                Log.d(TAG, "MQTT连接成功");
            }
        }).start();
    }
    /**
     * 启动定时重连任务，每隔10秒检查一次连接状态，如未连接则重新连接
     */
    private void startReconnect() {
        scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                if (!client.isConnected()) {
                    Mqtt_connect();
                }
            }
        }, 0*1000, 10 * 1000, TimeUnit.MILLISECONDS);
    }

    /**
     * 发布消息到指定的MQTT主题
     *
     * @param topic    主题名称
     * @param message2 消息内容（字符串）
     */
    private void publishmessageplus(String topic, String message2) {
        // 如果客户端未连接，则记录错误并返回
        if (client == null || !client.isConnected()) {
            Log.e(TAG, "MQTT客户端未连接");
            return;
        }
//        Log.d(TAG, "MQTT客户端连接成功");
        // 构造MQTT消息对象，并设置消息内容的字节数组
        MqttMessage message = new MqttMessage();
        message.setPayload(message2.getBytes());
        try {
            // 发布消息到指定主题
            client.publish(topic, message);
        } catch (MqttException e) {
            Log.e(TAG, "发布消息时出错", e);
        }
//        Log.d(TAG, "发布消息成功");
    }
}
